package com.awenhui.demo.demo.thread;

import lombok.SneakyThrows;

/**
 * @author yuxf
 * @version 1.0
 * @date 2021/7/1 10:52
 */
public class DeadLockTest {

    public static void main(String[] args) {

      Kid xm=  new Kid("小明",0);
     Kid xh=   new Kid("小红",1);

        new Thread(xm).start();
        new Thread(xh).start();
    }
}

class Kid implements Runnable {
    static String car = "小汽车";
    static String bear = "小熊";
    private String name;
    //0-先拿汽车，1-先拿小熊
    private int choice;

    public Kid(String name, int choice) {
        this.name = name;
        this.choice = choice;
    }

    @SneakyThrows
    @Override
    public void run() {
        if(choice==0)
        {
            synchronized (car) {
                System.out.println(name + "拿到了小汽车玩具");
                Thread.sleep(100);
                synchronized (bear) {
                    System.out.println(name+"拿到了小熊玩具");
                    Thread.sleep(100);
                }
            }

        }
        if(choice==1)
        {
            synchronized (bear) {
                System.out.println(name+"拿到了小熊玩具");
                Thread.sleep(100);
                synchronized (car) {
                    System.out.println(name + "拿到了小汽车玩具");

                    Thread.sleep(100);
                }
            }
        }

    }
}
